package cn.com.callback


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util

import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONObject
import cn.com.kh.KHUtil;
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTQueryInvitationHistory* @Description:华盛证券 客户邀请关系历史数据接口--内部接口
 * @author: chieh* @date 2022-3-8 15:50:22
 *
 */

public class aipHSTQueryInvitationHistory implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTQueryInvitationHistory.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
            JSONObject inObject = new JSONObject(inData);
            //鉴权变量
            String appid = getProperty.get("appid");
            String appsecret = getProperty.get("appsecret");

            //sign加密前后
            String signfront = "";
            String signafter = "";
            String sign_time=Instant.now().getEpochSecond();

            def updateBeginTime = GetJV(inObject, "updateBeginTime");
            def updateEndTime = GetJV(inObject, "updateEndTime");
            def CUSTOMER_IDsql = eliteBean.chaxun_sql("select count(CUSTOMER_ID) as CUSTOMER_ID_C from customer  where CUSTOMER_ID is not null  ", "dataSource");

            def selectcustomer_id="";
            int pageNo=0;
            int total= 50;
            log.debug("CUSTOMER_ID_C"+CUSTOMER_IDsql.get(0).get("CUSTOMER_ID_C"));
            String CUSTOMER_ID_C=CUSTOMER_IDsql.get(0).get("CUSTOMER_ID_C");

            int pageSize= Math.ceil(Integer.parseInt(CUSTOMER_ID_C)/ total) ;
            log.debug("pageSize"+pageSize);
            for (int i = 0; i < pageSize; i++) {
                Thread.sleep(5 * 1000);
                String CUSTOMER_ID_S="";
                selectcustomer_id = eliteBean.chaxun_sql("select CUSTOMER_ID from customer  where CUSTOMER_ID is not null  limit "+pageNo+" ,  "+total+"", "dataSource");
                for (int j = 1; j <= selectcustomer_id.size(); j++) {
                    CUSTOMER_ID_S=CUSTOMER_ID_S+selectcustomer_id.get(j-1).get("CUSTOMER_ID")+",";
                }
                pageNo=pageNo+50;
                CUSTOMER_ID_S=CUSTOMER_ID_S.substring(0, CUSTOMER_ID_S.length()-1);;
                log.debug("每次的华盛号："+CUSTOMER_ID_S)
                sign_time=Instant.now().getEpochSecond();
                HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                    {
                        put("sign_time", sign_time);
                        put("hsNoList", CUSTOMER_ID_S);
                    }
                };

                log.debug("paramHashMap：" + paramHashMap);
                //自然排序 升序参数
                signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
                log.debug("sign加密MD5前：" + signfront);
                signafter = Util.getMD5Str(signfront);
                log.debug("sign加密MD5后：" + signafter);
                paramHashMap.put("client_key", appid);
                paramHashMap.put("sign", signafter);

                String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
                log.debug("injson:" + injson);

                 totalData = Querypromocode(eliteBean, injson, dataSourceID);
                //解析SSO返回信息
                JSONObject jsonObject = new JSONObject(totalData);
                log.debug("jsonObject:" + jsonObject);

            }
            log.debug("当前时间1：" + updateBeginTime);
            log.debug("当前时间2：" + updateEndTime);
            log.debug("当前sql：" + selectcustomer_id);

            log.debug("解析信息-" + "sign_time: " + sign_time);


            outData = "{\"result\":\"1\",\"message\":\"处理成功\",\"data\":[]}";


        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

    //
    public static String Querypromocode(EliteBean eliteBean, String injson, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL + "/ae/query-invitation-history";
            log.debug("doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 60000, 0, headMap);
            log.debug("getResult:" + getResult);

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");
            JSONObject dataObject;

            log.debug("code:" + code);
            if (code == "00000") {
                SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = dateformat.format(System.currentTimeMillis());
                log.debug("result==================");
                JSONArray arrJsonArray = new JSONArray(result);

                int arrInt = arrJsonArray.length();
                log.debug("arrInt=================="+arrInt);
                for (int i = 0; i < arrInt; i++) {
                    JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);

                    String hsNo = GetJV(arrSmsJson, "hsNo");
                    String inviterName = GetJV(arrSmsJson, "inviterName");
                    String inviterHsNo = GetJV(arrSmsJson, "inviterHsNo");
                    String inviterType =GetJV(arrSmsJson,"inviterType");
                    String haveInvitation = GetJV(arrSmsJson, "haveInvitation");


                    // 查询名单是否已经存在
                     eliteBean.update("insert into query_invitation_history(hsNo,inviterName,inviterHsNo,inviterType,haveInvitation,createddate) " +
                            "values ('"+hsNo+"','"+inviterName+"','"+inviterHsNo+"','"+inviterType+"','"+haveInvitation+"',NOW())", "dataSource");
                }
                reJson = "{\"result\":\"1\",\"message\":成功}";

            } else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"用户获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"接口异常\"}";
        }
        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
